package com.tendory.common.per;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

public class ZPermissions {
    private static final String TAG = "ZPermissions";
    private static List<Permission> sPers = new ArrayList<>();
    private static int sReqCode = 100;

    public static Permission with(Object obj) {
        final Permission p = new PermissionCusRent(obj);
        p.requestCode(sReqCode++);
        p.setDestroyListener(new Permission.DestroyListener() {
            @Override
            public void onDestroy() {
                sPers.remove(p);
            }
        });
        sPers.add(p);
        return p;
    }

    public static void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults, Object object) {
//        List<String> deniedPermissions = new ArrayList<>(1);
//        for (int i = 0; i < grantResults.length; i++)
//            if (grantResults[i] != PackageManager.PERMISSION_GRANTED)
//                deniedPermissions.add(permissions[i]);
//        if (listener == null) {
//            callback(o, deniedPermissions.size() > 0 ? PermissionNo.class : PermissionYes.class, requestCode);
//        } else if (deniedPermissions.size() > 0) {
//            listener.onFailed(requestCode);
//        } else {
//            listener.onSucceed(requestCode);
//        }
        for (Permission per : sPers) {
            if (per.getRequestCode() == requestCode) {
                per.onRequestPermissionsResult(requestCode, permissions, grantResults, object);
                return;
            }
        }
    }

    public static boolean onActivityResult(int requestCode, int resultCode, Intent data, Object object) {
        for (Permission per : sPers) {
            if (per.getRequestCode() == requestCode) {
                per.onActivityResult(requestCode, resultCode, data, object);
                return true;
            }
        }
        return false;
    }

    public static boolean havePermisson(Context context, String per) {
        if (Build.VERSION.SDK_INT < 23) {
            return true;
        }
        int hasWriteContactsPermission = ContextCompat.checkSelfPermission(context, per);
        if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return true;
    }
}
